import { Schema, model } from 'mongoose';
import { ICardList, ICardListModel} from '@/types/model';

const cardListSchema = new Schema<ICardList, ICardListModel>({    
    listId: { type: String, required: true, unique: true },
    title: { type: String, required: true },
    order: { type: Number, required: true },
    createdAt: { type: Number, default: () => Date.now() },
    version: { type: Number, default: 0 }
}, {
    id: false,
    collection: 'cardlists',
    toJSON: { 
        getters: true, 
        virtuals: false,
        transform: (doc, ret) => {
            delete ret._id;
            delete ret.__v;
            return ret;
        }
    },
    toObject: { 
        getters: true, 
        virtuals: false,
        transform: (doc, ret) => {
            delete ret._id;
            delete ret.__v;
            return ret;
        }
    }
});

// 创建索引以优化查询性能
cardListSchema.index({ order: 1 });
cardListSchema.index({ listId: 1 }, { unique: true });

// 向后移动时更新order
cardListSchema.statics.updateOrderForBackwardMove = async function(listId: string, oldOrder: number, newOrder: number): Promise<unknown> {
    return this.updateMany(
        { 
            listId: { $ne: listId }, // 排除当前列表自身
            order: { $gt: oldOrder, $lte: newOrder } 
        },
        { $inc: { order: -1 } }
    );
};

// 向前移动时更新order
cardListSchema.statics.updateOrderForForwardMove = async function(listId: string, oldOrder: number, newOrder: number): Promise<unknown> {
    return this.updateMany(
        { 
            listId: { $ne: listId }, // 排除当前列表自身
            order: { $gte: newOrder, $lt: oldOrder } 
        },
        { $inc: { order: 1 } }
    );
};

// 获取最大order值并生成新的order
cardListSchema.statics.generateNextOrder = async function(): Promise<number> {
    const maxOrderList = await this.findOne().sort({ order: -1 });
    return maxOrderList ? maxOrderList.order + 1 : 0;
};

// 创建新的卡片列表（带事务）
cardListSchema.statics.createCardListWithTransaction = async function(title: string, listId: string): Promise<ICardList> {
    const session = await this.startSession();
    try {
        await session.startTransaction();
        const order = await this.generateNextOrder();
        const newCardList = await this.create([{
            listId,
            title,
            order
        }], { session });
        await session.commitTransaction();
        return newCardList[0];
    } catch (error) {
        await session.abortTransaction();
        throw error;
    } finally {
        await session.endSession();
    }
};

export default model<ICardList, ICardListModel>('CardList', cardListSchema);